﻿using Orchard.ContentManagement;
using Orchard.Data;
using Orchard.ImportExport.Services;
using System.Linq;
using System.Xml.Linq;
using Vitus.MediaProcessing.Models;

namespace Vitus.MediaProcessing.ImportExport
{
    public class MediaProfileAttachmentsExportEventHandler : IExportEventHandler
    {
        private readonly IRepository<MediaProfileAttachmentRecord> mediaProfileAttachmentRepository;
        private readonly IContentManager contentManager;

        public MediaProfileAttachmentsExportEventHandler(
            IRepository<MediaProfileAttachmentRecord> mediaProfileAttachmentRepository,
            IContentManager contentManager)
        {
            this.mediaProfileAttachmentRepository = mediaProfileAttachmentRepository;
            this.contentManager = contentManager;
        }

        public void Exporting(ExportContext context)
        {
        }

        public void Exported(ExportContext context)
        {
            if (!(context.ExportOptions.CustomSteps).Contains("MediaProfileAttachments"))
            {
                return;
            }
            
            var attachments = mediaProfileAttachmentRepository.Table.ToList();

            if (!attachments.Any())
            {
                return;
            }

            var contentIdentities = this.contentManager
                .GetMany<MediaProfileAttachmentsPart>(attachments.Select(a => a.MediaProfileAttachmentsPartRecord.Id), VersionOptions.Latest, QueryHints.Empty)
                .ToDictionary(c => c.Id, c => this.contentManager.GetItemMetadata(c).Identity.ToString());

            var root = new XElement("MediaProfileAttachments");
            context.Document.Element("Orchard").Add(root);

            foreach (var attachment in attachments)
            {
                string identity;

                if (contentIdentities.TryGetValue(attachment.MediaProfileAttachmentsPartRecord.Id, out identity))
                {
                    root.Add(new XElement("Attachment",
                        new XAttribute("MediaProfileAttachmentsPartRecord_Identity", identity),
                        new XAttribute("MediaPath", attachment.MediaPath),
                        new XAttribute("ProfileName", attachment.ProfileName)
                        ));
                }
            }
        }
    }
}

